package servlet;

import java.io.IOException;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.jsp.JspFactory;
import javax.servlet.jsp.PageContext;

import com.jspsmart.upload.File;
import com.jspsmart.upload.Files;
import com.jspsmart.upload.Request;
import com.jspsmart.upload.SmartUpload;
import com.jspsmart.upload.SmartUploadException;

import beans.Chapterbean;

import dao.Chapter;
import dao.Course;

public class ChapterManageServlet extends HttpServlet {

    /**
     * 
     */
    private static final long serialVersionUID = 1L;

    /**
     * The doGet method of the servlet. <br>
     * 
     * This method is called when a form has its tag value method equals to get.
     * 
     * @param request
     *            the request send by the client to the server
     * @param response
     *            the response send by the server to the client
     * @throws ServletException
     *             if an error occurred
     * @throws IOException
     *             if an error occurred
     */
    public void doGet(HttpServletRequest request, HttpServletResponse response)
	    throws ServletException, IOException {

	this.doPost(request, response);
    }

    /**
     * The doPost method of the servlet. <br>
     * 
     * This method is called when a form has its tag value method equals to
     * post.
     * 
     * @param request
     *            the request send by the client to the server
     * @param response
     *            the response send by the server to the client
     * @throws ServletException
     *             if an error occurred
     * @throws IOException
     *             if an error occurred
     */
    public void doPost(HttpServletRequest request, HttpServletResponse response)
	    throws ServletException, IOException {
	if (request.getQueryString() != null) {
	    StringBuffer pathString = new StringBuffer("/image/structureChart/");
	    String action = request.getParameter("action");
	    String courseid = ((Course)request.getSession().getAttribute("course")).getCourseid();
	    Chapterbean chapterbean = new Chapterbean();
	    SmartUpload su = new SmartUpload();
//	    PageContext pageContext1 = JspFactory.getDefaultFactory()  
//	                .getPageContext(this, requ, resp, null, true, 8192, true);
	    su.initialize(this.getServletConfig(), request, response);
	    su.setMaxFileSize(5000000);
	    // su.setTotalMaxFileSize(20000);
	    su.setAllowedFilesList("jpg,jpeg,png");

	    try {
		// su.setDeniedFilesList("exe,bat,jsp,html,htm,php");
		su.upload();
		//String path = request.getSession().getServletContext().getRealPath("/image/structureChart/");
		//获取绝对路径
		//su.save("/image/structureChart/",SmartUpload.SAVE_VIRTUAL);
		//su.save(path);
		//response.getWriter().write("success.");
		

	    } catch (SmartUploadException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	    }
	    // catch (SQLException e) {
	    // // TODO Auto-generated catch block
	    // e.printStackTrace();
	    // }
	    Request request2 = su.getRequest();
	    String chapterId = request2.getParameter("chapterId").trim();
	    String chapterName = new String(request2.getParameter("chapterName").trim().getBytes("gbk"),"utf-8");	    
	    String demand = new String(request2.getParameter("demand").trim().getBytes("gbk"),"utf-8");
	    Files files = su.getFiles();
		File file = files.getFile(0);
		if (!file.isMissing()) {
		    int pos = file.getFileName().lastIndexOf(".");
		    pathString.append(chapterId).append(file.getFileName().substring(pos));
		    
		    java.io.File imgFile = new java.io.File(request.getSession().getServletContext().getRealPath(pathString.toString()));
		    if(imgFile.exists()){
			imgFile.delete();
		    }
		    
		    try {
			file.saveAs(pathString.toString(), SmartUpload.SAVE_VIRTUAL);
		    } catch (SmartUploadException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		    }		    
		}
	    Chapter chapter = new Chapter();
	    chapter.setChapterid(chapterId);
	    chapter.setCourseid(courseid);
	    chapter.setName(chapterName);
	    chapter.setStructurechart(pathString.toString());
	    chapter.setDemand(demand);
	    if ("add".equals(action)) {
		if (chapterbean.addChapter(chapter)) {
		    request.setAttribute("success", "true");
		} else {
		    request.setAttribute("success", "false");
		}
		request.getRequestDispatcher("../teacher/uploadChapter.jsp").forward(
			request, response);
	    } else if ("modify".equals(action)) {
		if (chapterbean.update(chapter)) {
		    request.setAttribute("success", "true");
		} else {
		    request.setAttribute("success", "false");
		}
		request.getRequestDispatcher("../gradehead/modifyCourse.jsp")
			.forward(request, response);
	    }
	}
    }

}
